package com.example.experiment5;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.widget.VideoView;

import java.io.File;

public class VideoActivity extends AppCompatActivity implements View.OnClickListener {

    private VideoView videoView;
    private Button    videoPlay;
    private Button    videoPause;
    private Button    videoReplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TestVideo();
    }

    public void TestVideo() {
        setContentView(R.layout.activity_video);

        videoPlay   = (Button)findViewById(R.id.video_play);
        videoPause  = (Button)findViewById(R.id.video_pause);
        videoReplay = (Button)findViewById(R.id.video_replay);
        videoView   = (VideoView)findViewById(R.id.video_view);

        videoPlay.setOnClickListener(this);
        videoPause.setOnClickListener(this);
        videoReplay.setOnClickListener(this);

        getVideoPath();
    }

    private void getVideoPath() {
        // 先将本地的视频上传到模拟器中
        // 视频上传路径：/sdcard/Android/data/com.example.experiment5/files/androidstudio.3gp
        File file = new File(getExternalFilesDir(null),
                "androidstudio.3gp");

        Log.d("Video", file.getAbsolutePath());

        if (!file.exists()) {
            Toast.makeText(this, "视频文件路径错误",Toast.LENGTH_SHORT).show();

            return;
        }else {
            Toast.makeText(this, "视频文件路径正确",Toast.LENGTH_SHORT).show();
        }
        if (ContextCompat.checkSelfPermission(VideoActivity.this, Manifest.permission.
                WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(VideoActivity.this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);//权限返回码为1
        }
        else {
            // 设置视频文件
            videoView.setVideoPath(file.getPath());
            videoView.start();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.video_play:
                if (!videoView.isPlaying()) {
                    videoView.start();
                }
                break;
            case R.id.video_pause:
                if (videoView.isPlaying()) {
                    videoView.pause();
                }
                break;
            case R.id.video_replay:
                if (videoView.isPlaying()) {
                    videoView.resume();
                }
                break;
        }
    }
}
